// pages/pay/merOffline/index.js
const app = getApp(), fetchApi = require("../../../utils/httpPost.js"),
common_Js = require("../../../component/common.js");
import Toast from '../../../component/vant/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: false,
    netWork: true,
    isLoading: true,
    mer:{},
    payPrice:undefined,
    remark:'',
    mer_no:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var isLogin = app.getStorageSync("isLogin");
    if(isLogin == 0){
      wx.navigateTo({
        url: '/pages/login/index',
      })
    }else{
    }
    
    if(options.q){
      var q = decodeURIComponent(options.q) // 获取到二维码原始链接内容
      q = "?" + q.split("?")[1];
      this.data.query = q;
      console.log('q',q)
      options = common_Js.getQueryVariable(q);
    }

    this.data.mer_no = options.no;
    // this.onHttpInit(options.no);
  },
  onShow(){
    // this.setData({
    //   isLoading: false
    // })
      if(this.data.mer_no!=''){
        this.onHttpInit(this.data.mer_no);
      }
    // this.onHttpInit(this.data.mer_no);
  },
  inputMoney(e){    
    console.log('inputMoney',e);
    var money = e.detail.value;
    if(money == ""){
      money = "0";
    }
    let value = e.detail.value
    if (value != '') {
      value = value.replace(/[^\d.]/g, "")
      if (/^(\d?)+(\.\d{0,2})?$/.test(value)) {} else {
        value = value.substring(0, value.length - 1);
      }
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      if (value.indexOf(".") < 0 && value != "") {
        value = parseFloat(value);
      }
      // if (Number(value) > 20000) {
      //   value = 20000
      // }
      // if (Number(value) < 1) {
      //   value = 1
      // }
    }
    console.log('value',value)
    this.data.payPrice = value;
    this.setData({
      payPrice: value
    })
  },
  inputRemark(e){
    console.log('inputRemark e',e)
    this.data.remark = e.detail.value;
  },
  formatter(value) {
    // 过滤输入的非数字
    console.log('value 替换之前 ',value);
    console.log('value  替换之后',value.replace(/[^\d.]+$/g, ""))
    var price = value.replace(/[^\d.]+$/g, "");
    if(price.indexOf(".") >= 0){
      var index = price.indexOf(".");
      if(index == 0){
        price = "0" + price;
      }
      console.log('index',index);
      price = price.substr(0,index + 3);
    }
    return price;
  },
  onHttpInit(shopNo){
    var that = this
    fetchApi.httpPost('/mer/detailByNo', {
      shop_no: shopNo,
    }, function (res) {
      console.log("商家信息", res)
      if (res.data.code == 0) {
        that.setData({
          mer: res.data.data.mer
        })
      } else {
        Toast.fail(res.data.msg);
      }
      that.setData({
        isLoading: false, loading: true, netWork: true,
      });
    }, function () { })
  },
  submitOp(){
    if(this.data.payPrice == undefined || this.data.payPrice == '' ){
      Toast.fail('支付金额不能为空')
      return;
    }
    this.onHttpBuyMerOffline();
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpBuyMerOffline: function () {
    var that = this;
    fetchApi.httpPost('/product/order/addOrderBuyMerOffline', {
      mer_id: that.data.mer.id,
      price: that.data.payPrice, //  积分商品订单
      remark:that.data.remark,
    }, function (res) {
      console.log("商家线下活动支付 ", res)
      if (res.data.code == 0) {
        var orderId = res.data.data;
        that.requestPay(orderId);
      }  else if(res.data.code == 2){
        that.handleEstate();
      } else {
        console.log("商家线下活动支付 异常", res.data.msg)
        Toast.fail(res.data.msg)
      }
    }, function () {
      that.setData({ isLoading: false, loading: true, netWork: true, })
    })
  },
  handleEstate(){
    var that = this;
    var message = "绑定小区后再进行购买"
    Dialog.confirm({
      title: '绑定小区',
      message
    }).then(() => {
      wx.navigateTo({
        url: '/pages/account/index?from_type=product',
      })
    })
    .catch(() => {
      Dialog.close();
    });
  },
  requestPay:function(order_id){
    var that = this;
    fetchApi.httpPost('/pay/requestPayOffline', {
      order_id: order_id,
      remark:that.data.remark,
      subject:'线下活动支付'
    }, function (res) {
      console.log('商家线下活动支付信息返回',res)
      if (res.data.code == 0) {
        var pay_data = res.data.data;
        var wxpayinfo = JSON.parse(res.data.data)
        console.log('pay_data',pay_data)
        if(wxpayinfo.result_code == 'SUCCESS'){
          wx.requestPayment({
            timeStamp: wxpayinfo.timeStamp,
            nonceStr: wxpayinfo.nonceStr,
            package: wxpayinfo.package,
            signType: wxpayinfo.signType,
            paySign: wxpayinfo.paySign,
            success (res) { 
              console.log('requestPayment success',res)
              wx.redirectTo({
                url: '/pages/pay/payResult/index?order_id=' + order_id,
              })
            },
            fail (res) {
              console.log('requestPayment fail',res)
             }
          })
        }
      } else {
        that.setData({ isLoading: false, loading: true, netWork: true })
      }
    }, function () {
        that.setData({  isLoading: false,  loading: true,  netWork: true, }) 
    })
  },
})